package com.navinfo.platform.aero.data.rest.core.controller;

import com.navinfo.platform.aero.data.rest.core.constant.AppServiceDefine;
import com.navinfo.platform.aero.data.rest.core.dto.CommandResult;
import com.navinfo.platform.aero.data.rest.core.enumref.EnumGather;
import com.navinfo.platform.aero.data.rest.core.enumref.ResultCode;
import com.navinfo.platform.aero.data.rest.core.service.impl.QureyDataService;
import com.navinfo.platform.aero.data.rest.core.util.StringUtils;
import com.navinfo.platform.aero.data.rest.vo.ParentCommand;
import com.navinfo.platform.aero.data.rest.vo.StatisticsCommand;
import com.navinfo.platform.aero.data.rest.vo.ChildCommand;
import com.navinfo.platform.aero.data.rest.vo.ColumnsCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 单车统计信息controller
 * @date 2018年11月23日
 * @author CaiHS
 */

@RestController
@RequestMapping(value = AppServiceDefine.API_SERVER_PREFIX + "/single")
public class SingleStatisticsController {

    private static final Logger logger = LoggerFactory.getLogger(SingleStatisticsController.class);
    @Autowired
    private QureyDataService service;

    /**
     * 查询单车统计信息(按项目查询)
     * @param command 参数
     * @return 字段映射
     */
    @RequestMapping(value = "/statisticscol",method = RequestMethod.POST)
    public CommandResult getStatisticsByColumns(@RequestBody ColumnsCommand command) {
        logger.debug("查询单车统计信息(按项目查询)Handler层开始" + SingleStatisticsController.class.getName(), "Method:getStatisticsByColumns");
        CommandResult commandResult = new CommandResult();
        try {
            commandResult = checkCommand(commandResult, command);
            if(commandResult.getResultCode() == ResultCode.CLIENT_ERROR.code()){
                return commandResult;
            } else {
                List<Map<String,Object>> data = service.queryList(command.getUid(), command.getStart(), command.getEnd(),
                        command.getColumns(), command.getCycle(), null, null);
                if(data != null && data.size() > 0){
                    commandResult.setData(data);
                }
                commandResult.fillResult(ResultCode.OK);
            }
        } catch (Exception e) {
            logger.error("查询单车统计信息(按项目查询)！{}", command, e);
            commandResult.setResultCode(ResultCode.SERVER_ERROR.code());
            commandResult.setMessage(ResultCode.SERVER_ERROR.result());
        }
        return commandResult;
    }
    /**
     * 查询单车统计信息(按分类查询)
     * @param command 参数
     * @return 字段映射
     */
    @RequestMapping(value = "/statisticschd",method = RequestMethod.POST)
    public CommandResult getStatisticsByChild(@RequestBody ChildCommand command) {
        logger.debug("查询单车统计信息(按项目查询)Handler层开始" + SingleStatisticsController.class.getName(), "Method:getStatisticsByChild");
        CommandResult commandResult = new CommandResult();
        try {
            commandResult = checkCommand(commandResult, command);
            if(commandResult.getResultCode() == ResultCode.CLIENT_ERROR.code()){
                return commandResult;
            } else {
                List<Map<String,Object>> data = service.queryList(command.getUid(), command.getStart(), command.getEnd(),
                        null, command.getCycle(), null, command.getChilds());
                if(data != null && data.size() > 0){
                    commandResult.setData(data);
                }
                commandResult.fillResult(ResultCode.OK);
            }
        } catch (Exception e) {
            logger.error("查询单车统计信息(按项目查询)！{}", command, e);
            commandResult.setResultCode(ResultCode.SERVER_ERROR.code());
            commandResult.setMessage(ResultCode.SERVER_ERROR.result());
        }
        return commandResult;
    }
    /**
     * 查询单车统计信息(按父分类查询)
     * @param command 参数
     * @return 字段映射
     */
    @RequestMapping(value = "/statisticsparents",method = RequestMethod.POST)
    public CommandResult getStatisticsByParents(@RequestBody ParentCommand command) {
        logger.debug("查询单车统计信息(按父分类查询)Handler层开始" + SingleStatisticsController.class.getName(), "Method:getStatisticsByParents");
        CommandResult commandResult = new CommandResult();
        try {
            commandResult = checkCommand(commandResult, command);
            if(commandResult.getResultCode() == ResultCode.CLIENT_ERROR.code()){
                return commandResult;
            } else {
                List<Map<String,Object>> data = service.queryList(command.getUid(), command.getStart(), command.getEnd(),
                        command.getCycle(), command.getParents());
                if(data != null && data.size() > 0){
                    commandResult.setData(data);
                }
                commandResult.fillResult(ResultCode.OK);
            }
        } catch (Exception e) {
            logger.error("查询单车统计信息(按父分类查询)！{}", command, e);
            commandResult.setResultCode(ResultCode.SERVER_ERROR.code());
            commandResult.setMessage(ResultCode.SERVER_ERROR.result());
        }
        return commandResult;
    }
    /**
     * 入参校验
     * @param commandResult 校验结果
     * @param command 参数
     * @return 校验结果
     */
    private static CommandResult checkCommand (CommandResult commandResult, ColumnsCommand command){
        logger.info(SingleStatisticsController.class.getName() + " checkCommand start");
        List<String> columns = command.getColumns();
        if (columns == null || columns.size() <= 0) {
            commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
            commandResult.setMessage("必须指定统计项目");
            return commandResult;
        }
        checkBaseCommand(commandResult, command);
        logger.info(SingleStatisticsController.class.getName() + " checkCommand end");
        return commandResult;
    }
    private static CommandResult checkCommand (CommandResult commandResult, ChildCommand command){
        logger.info(SingleStatisticsController.class.getName() + " checkCommand start");

        List<String> childs = command.getChilds();
        if (childs == null || childs.size() == 0) {
            commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
            commandResult.setMessage("必须指定子分类");
            return commandResult;
        }
        checkBaseCommand(commandResult, command);

        logger.info(SingleStatisticsController.class.getName() + " checkCommand end");
        return commandResult;
    }
    private static CommandResult checkCommand (CommandResult commandResult, ParentCommand command){
        logger.info(SingleStatisticsController.class.getName() + " checkCommand start");

        List<String> parents = command.getParents();
        if (parents == null || parents.size() == 0) {
            commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
            commandResult.setMessage("必须指定父分类");
            return commandResult;
        }
        checkBaseCommand(commandResult, command);

        logger.info(SingleStatisticsController.class.getName() + " checkCommand end");
        return commandResult;
    }
    private static CommandResult checkBaseCommand (CommandResult commandResult, StatisticsCommand command){
        // uid
        Long uid = command.getUid();
        if (uid == null) {
            commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
            commandResult.setMessage("必须指定唯一ID");
            return commandResult;
        }
        String cycle = command.getCycle();
        if(StringUtils.isNull(cycle)
                || (!EnumGather.DAY.getName().equals(cycle)
                && !EnumGather.WEEK.getName().equals(cycle)
                && !EnumGather.MONTH.getName().equals(cycle))){
            command.setCycle(EnumGather.DAY.getName());
        }
        String start = command.getStart();
        Pattern p = Pattern.compile("^\\d{4}(\\-)\\d{1,2}\\1\\d{1,2}$");
        if(!StringUtils.isNull(start) ){
            //Pattern p = Pattern.compile("^\\d{4}(\\-)\\d{1,2}$");
            Matcher m = p.matcher(start);
            if(!m.matches()){
                commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
                commandResult.setMessage("开始日期格式错误，正确格式为：yyyy-MM-dd");
                return commandResult;
            }
        } else {
            commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
            commandResult.setMessage("开始日期格式错误，正确格式为：yyyy-MM-dd");
            return commandResult;
        }
        String end = command.getEnd();

        if(!StringUtils.isNull(end) ){
            Matcher m = p.matcher(end);
            if(!m.matches()){
                commandResult.setResultCode(ResultCode.CLIENT_ERROR.code());
                commandResult.setMessage("结束日期格式错误，正确格式为：yyyy-MM-dd");
                return commandResult;
            }
        } else {
            command.setEnd(start);
        }
        return commandResult;
    }
}

